package pers.xuehongyan.useat.server.auth;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Component;
import pers.xuehongyan.useat.server.enity.User;
import pers.xuehongyan.useat.server.exception.user.UserNotFoundException;
import pers.xuehongyan.useat.server.mapper.UserMapper;

import javax.annotation.Resource;

/**
 * @author xuehongyan
 */
@Component
public class JwtUserUtils {
    final static long TOKEN_EXPIRE_MILLIS = 1000 * 60 * 60 * 24 * 7;

    @Resource
    UserMapper userMapper;

    public String getTokenByUser(User user) {
        String username = user.getName();
        return JwtUtils.encode("username", username, TOKEN_EXPIRE_MILLIS);
    }

    public User getUserByToken(String token) throws UserNotFoundException {
        String username = JwtUtils.decode(token, "username");
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("name", username));
        if(user == null) {
            throw new UserNotFoundException(username);
        }
        return user;
    }
}
